package com.xhs.controller;

import cn.hutool.http.HttpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 图片代理控制器
 * 用于解决小红书图片防盗链问题
 *
 * @author xhs
 */
@Slf4j
@RestController
@RequestMapping("/api/image")
@Tag(name = "图片代理", description = "图片代理服务，解决防盗链问题")
public class ImageController {

    /**
     * 图片代理接口
     */
    @Operation(summary = "图片代理", description = "代理获取小红书图片，解决防盗链问题")
    @GetMapping("/proxy")
    public ResponseEntity<byte[]> proxyImage(@RequestParam("url") String imageUrl) {
        try {
            // 参数验证
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                log.warn("图片URL为空");
                return ResponseEntity.badRequest().build();
            }
            
            log.info("代理获取图片: {}", imageUrl);

            // 使用Hutool下载图片，设置必要的请求头（不使用代理）
            byte[] imageBytes = HttpUtil.createGet(imageUrl)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
                    .header("Referer", "https://www.xiaohongshu.com/")
                    .header("Accept", "image/webp,image/apng,image/*,*/*;q=0.8")
                    .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .header("Connection", "keep-alive")
                    .header("Sec-Fetch-Dest", "image")
                    .header("Sec-Fetch-Mode", "no-cors")
                    .header("Sec-Fetch-Site", "cross-site")
                    .timeout(15000) // 恢复超时设置
                    .execute()
                    .bodyBytes();

            if (imageBytes == null || imageBytes.length == 0) {
                log.warn("图片下载为空: {}", imageUrl);
                return ResponseEntity.notFound().build();
            }

            log.info("图片代理成功，大小: {} bytes", imageBytes.length);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            
            // 根据URL判断图片类型
            if (imageUrl.contains("webp")) {
                headers.setContentType(MediaType.parseMediaType("image/webp"));
            } else if (imageUrl.contains("jpg") || imageUrl.contains("jpeg")) {
                headers.setContentType(MediaType.IMAGE_JPEG);
            } else if (imageUrl.contains("png")) {
                headers.setContentType(MediaType.IMAGE_PNG);
            } else {
                headers.setContentType(MediaType.IMAGE_JPEG); // 默认JPEG
            }
            
            headers.setContentLength(imageBytes.length);
            headers.setCacheControl("public, max-age=3600"); // 缓存1小时
            
            // 添加CORS头
            headers.add("Access-Control-Allow-Origin", "*");
            headers.add("Access-Control-Allow-Methods", "GET");
            headers.add("Access-Control-Allow-Headers", "Content-Type");

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            log.error("图片代理失败: {}, 错误: {}", imageUrl, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 